const express = require('express');
const {
    asyncHandler
} = require('../getSendResult');
const userServ = require('../../services/userService');
const router = express.Router();
const jwt = require('../jwt');

// 登录
router.post('/login', asyncHandler(async (req, res) => {
    const result = await userServ.login(req.body.loginId, req.body.loginPwd);
    if (result) {
        // 登录成功 颁发jwt
        jwt.publish(res, undefined, {
            id: result.id
        });
    }
    return result;
}));

// 注册
router.post('/register', asyncHandler(async (req, res) => {
    const result = await userServ.addUser({
        name:req.body.name,
        loginId:req.body.loginId,
        loginPwd:req.body.loginPwd
    });
    if (result) {
       return {
           code:200,
           msg:'registered',
       }
    }
    return null;
}));

router.get('/whoami', asyncHandler(async (req, res) => {
    return await userServ.getUserById(req.userId);
}));

module.exports = router;